package com.example.psysystemhomework.adapter;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;

import com.bumptech.glide.Glide;

import com.example.psysystemhomework.R;
import com.example.psysystemhomework.bean.CountBeanStatic;
import com.example.psysystemhomework.bean.RBean;
import com.example.psysystemhomework.bean.StoryBean;
import com.example.psysystemhomework.bean.UserBean;
import com.example.psysystemhomework.util.NetUtil;
import com.example.psysystemhomework.util.ShareUtil;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;

import lombok.Data;
import lombok.SneakyThrows;

@Data
public class HomeAdapter extends BaseAdapter {
    private static final String TAG = "storyBean 获取过来的";
    JSONObject json;
    Context context;
    private List<StoryBean> storyBean;
    private final ShareUtil shareUtil;
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(@NonNull Message msg) {
            JSONObject jsonObject = (JSONObject) msg.obj;
            Log.i(TAG, "save:  evbus 集结地");
            if (jsonObject != null) {
                Gson gson = new Gson();
                RBean r = gson.fromJson(jsonObject.toString(), RBean.class);
                if (r.isFlag()) {
                    for (int i = 0; i < storyBean.size(); i++) {
                        if (msg.arg1 == storyBean.get(i).getStoryId()) {
                            storyBean.remove(i);
                        }
                    }

                    Toast.makeText(context, r.getMsg(), Toast.LENGTH_SHORT).show();
                    notifyDataSetChanged();


                } else {
                    Toast.makeText(context, r.getMsg(), Toast.LENGTH_SHORT).show();

                }


            }


            super.handleMessage(msg);
        }
    };

    public void setJson(JSONObject json) {
        this.json = json;
        Log.i("给适配器传递过来json", "HomeAdapter: " + json.toString());
        String data = null;
        String o = null;
        try {
            data = json.getString("data");
            JSONObject jsonObject = new JSONObject(data);
            o = jsonObject.get("list").toString();
        } catch (JSONException e) {
            e.printStackTrace();
        }

        Gson gson = new Gson();
        storyBean = gson.fromJson(o, new TypeToken<List<StoryBean>>() {
        }.getType());

        UserBean user = shareUtil.getUser();
        int count = 0;
        if (user != null) {
            for (int i = 0, len = storyBean.size(); i < len; ++i) {
                if (storyBean.get(i).getUserBean().getUserId() == user.getUserId()) {
                    count++;
                }

            }
        }


        CountBeanStatic.upload_count = count;
        Log.i(TAG, "setJson: " + storyBean);
    }


    public void setShowMe() {
        UserBean user = shareUtil.getUser();
        for (int i = 0, len = storyBean.size(); i < len; ++i) {
            if (storyBean.get(i).getUserBean().getUserId() != user.getUserId()) {
                storyBean.remove(i);
                --len;
                --i;
            }

        }


        notifyDataSetChanged();

    }

    public HomeAdapter(JSONObject json, Context context) {
        this.json = json;
        this.context = context;
        shareUtil = new ShareUtil(context);
        if (json.isNull("data")) {
            storyBean = new ArrayList<>();
        }


    }


    @SneakyThrows
    @Override
    public int getCount() {
        return storyBean.size();
    }

    @Override
    public Object getItem(int i) {
        return storyBean.get(i);
    }

    @SneakyThrows
    @Override
    public long getItemId(int i) {
        return i;
    }

    @SneakyThrows
    @Override
    public View getView(int i, View view, ViewGroup viewGroup) {
        final int[] index = {0};
        view = View.inflate(context, R.layout.item_story_show, null);
        ViewHolder viewHolder = new ViewHolder(view);
        viewHolder.mName.setText(storyBean.get(i).getUserBean().getName());
        String url = storyBean.get(i).getUserBean().getIconBean().getUrl();
        Glide.with(context)
                .load(url)
                .into(viewHolder.mImageTou);
        view.setOnLongClickListener(view12 -> {
            if (index[0] % 2 == 0) {
                if (shareUtil.getUser() != null) {
                    if (shareUtil.getUser().getUserId() == storyBean.get(i).getUserBean().getUserId()) {
                        viewHolder.line_layout_delete.setVisibility(View.VISIBLE);
                    } else {
                        Toast.makeText(context, "请选择自己的文章删除", Toast.LENGTH_SHORT).show();
                    }

                }
            } else {
                viewHolder.line_layout_delete.setVisibility(View.GONE);

            }


            index[0]++;
            return true;
        });
        view.setOnClickListener(view1 -> {
            AlertDialog.Builder builder = new AlertDialog.Builder(context);
            StoryBean item = storyBean.get(i);
            builder.setTitle(item.getUserBean().getName() + "：" + item.getType());
            builder.setMessage(item.getContent());
            builder.setPositiveButton("ok", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i12) {

                }
            });
            builder.show();


        });
        viewHolder.line_layout_delete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                AlertDialog.Builder builder = new AlertDialog.Builder(context);
                StoryBean item = storyBean.get(i);
                builder.setTitle("警告");
                builder.setMessage("确定要删除此项么");
                builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i1) {
                        new Thread() {
                            @Override
                            public void run() {

                                NetUtil netUtil = new NetUtil(context);
                                JSONObject jsonObject = netUtil.deleteStory(storyBean.get(i));
                                Message msg = new Message();
                                msg.obj = jsonObject;
                                msg.arg1 = storyBean.get(i).getStoryId();
                                handler.sendMessage(msg);


                                super.run();
                            }
                        }.start();
                    }
                });
                builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {

                    }
                });
                builder.show();


            }
        });
        viewHolder.mTitle.setText(storyBean.get(i).getType().trim());
        String replace = storyBean.get(i).getContent().trim().replace("\r\n", "");
        if (replace.length() > 42) {
            viewHolder.mContent.setText(replace.substring(0, 42) + "...");
        } else {
            viewHolder.mContent.setText(replace);
        }


        return view;
    }

    public static class ViewHolder {
        ImageView mImageTou;

        TextView mName;
        TextView mTitle;
        TextView mContent;
        LinearLayout line_layout_delete;

        public ViewHolder(View itemView) {
            this.mImageTou = itemView.findViewById(R.id.image_tou);
            this.mName = itemView.findViewById(R.id.name);
            this.mTitle = itemView.findViewById(R.id.title);
            this.mContent = itemView.findViewById(R.id.content);
            this.line_layout_delete = itemView.findViewById(R.id.line_layout_delete);
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void save(JSONObject jsonObject) {


    }
}
